#!/usr/bin/env python
#encoding=utf-8

import os
import urllib
import urllib2
import cookielib

#配置urllib2的opener
def install_opener():
    cookie_jar = cookielib.MozillaCookieJar()
    processor = urllib2.HTTPCookieProcessor(cookie_jar)
    opener = urllib2.build_opener(processor)
    urllib2.install_opener(opener)
    pass

def get_webpage(url, url_data=None):
    request = urllib2.Request(url, data=url_data)
    while True:
        try:
            respond = urllib2.urlopen(request, timeout=5)
            if respond != None:
                return respond.read()
        except KeyboardInterrupt:
            print('User cancel.')
            break
        except:
            print('Error occur, try again.')
    pass

def write_file(context, filename):
    with open(filename, 'w') as f:
        f.write(context)

def download_file(url, filename):
    #下载进度回调函数
    def call_back(blocknum, blocksize, totalsize):
        if totalsize == 0:
            return
        percent = 100.0 * blocknum * blocksize / totalsize
        if (percent > 100.0):
            percent = 100.0
        #在同一行刷新下载状态，注意print()后有个逗号
        print('\r%5.1f%%, %s' % (percent,filename)),    

    try:
        #临时下载数据到xxx.zip.tmp文件中
        #下载完成后再重命名为xxx.zip，这样可以避免出现不完整的文件
        temp_filename = filename + '.tmp'
        urllib.urlretrieve(url, temp_filename, call_back)

        os.rename(temp_filename, filename)
        print('\n== Done ==')
        return True

    except:
        print('\n== Error ==')
        return False
    pass

def get_url_filename(url):
    return urllib.unquote(url).split('/')[-1]
